package com.bieyang.anjia.ui.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;

import org.json.JSONArray;
import org.json.JSONObject;

import com.bieyang.anjia.R;
import com.bieyang.anjia.module.Device;
import com.bieyang.anjia.net.NetManager;
import com.bieyang.anjia.utils.Constants;
import com.bieyang.anjia.utils.SharedPrefsUtil;
import com.bieyang.anjia.utils.Show;
import com.bieyang.anjia.utils.ShowProgress;
import com.bieyang.anjia.utils.SubUtils;
import com.umeng.analytics.MobclickAgent;

import android.annotation.SuppressLint;
import android.app.ExpandableListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;
/**
 * 警告威慑
 * @author myq
 *
 */
public class AlarmVoiceActivity extends ExpandableListActivity {
	ExpandableListView listview;
	View headerView;
	VoiceAdapter adapter;
	boolean isSetted;
	CheckBox cb;
	public int groupPosition = -1, childPosition = -1;
	/**
	 * 一级目录
	 */
	List<Map<String, String>> groups;
	/**
	 * 二级目录
	 */
	List<List<Map<String, Object>>> childs;
	public Context con;
	public SubUtils subUtils;
	/**
	 * 进度条
	 */
	public ShowProgress progressDialog;
	public String uuid, id, name;
	/**
	 * 当前选中语音
	 */
	String currentPlay;
	/**
	 * 播放器
	 */
	MediaPlayer player = new MediaPlayer();
	CheckBox previousPlay;
	HashMap<String, Object> voiceMap = new HashMap<String, Object>();
	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case Constants.SET_SUB_SET_SUCCESS:
				progressDialog.dismiss();
				Log.d("saveSetting", "success");
				SharedPrefsUtil
						.putValue(
								con,
								Constants.AlARM_PLAY_VOICE,
								groupPosition == -1 ? getString(R.string.sub_states_null)
										: childs.get(groupPosition)
												.get(childPosition)
												.get(Constants.SUB_NAME)
												.toString());
				setResult(2003);
				Show.toast(con, R.string.save_device_ok);
				finish();
				break;
			case Constants.SET_SUB_SET_FAILED:
				progressDialog.dismiss();
				Show.toast(con, R.string.save_device_fail);
				finish();
				break;
			case Constants.GET_ALARM_MUSIC_SUCCESS:
				progressDialog.dismiss();
				JSONArray data = (JSONArray) msg.obj;
				if (null != data) {
					add(data);
				}
				break;
			case Constants.GET_ALARM_MUSIC_FAIL:
				progressDialog.dismiss();
				break;
			default:
				break;
			}
		};
	};

	private void add(JSONArray data) {
		for (int i = 0; i < data.length(); i++) {
			try {
				JSONObject json = data.getJSONObject(i);
				String firstDir = json.getString("typeCode");
				String secDir = json.getString("name");
				voiceMap.put(secDir, json.getString("url"));
				boolean isContains = false;
				int count = -1;
				for (Map<String, String> group : groups) {
					if (group.containsValue(firstDir)) {
						count = groups.indexOf(group);
						isContains = true;
						break;
					}
				}

				if (!isContains) {
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("group", firstDir);
					groups.add(map);
					ArrayList<Map<String, Object>> itemNew = new ArrayList<Map<String, Object>>();
					addMapToList(secDir, itemNew.size(), itemNew,
							groups.indexOf(map));
					childs.add(itemNew);
				} else {
					List<Map<String, Object>> child = childs.get(count);
					boolean isContainSec = false;
					for (Map<String, Object> childItem : child) {
						if (childItem.containsValue(secDir)) {
							isContainSec = true;
							break;
						}
					}
					if (!isContainSec) {
						addMapToList(secDir, child.size(), child, count);
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		adapter = new VoiceAdapter(this, groups, R.layout.groups_layout,
				new String[] { "group" }, new int[] { R.id.look_more }, childs,
				R.layout.alarm_voice_list_item, new String[] {
						Constants.SUB_NAME, Constants.SUB_CHECK }, new int[] {
						R.id.voice_item_name, R.id.voice_item_check });
		setListAdapter(adapter);
		for (int i = 0; i < adapter.getGroupCount(); i++) {
			listview.expandGroup(i);
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		con = this;
		subUtils = new SubUtils();
		if (null == progressDialog) {
			progressDialog = SubUtils.showProgress(con);
		} else {
			progressDialog.show();
		}
		Intent intent = getIntent();
		uuid = intent.getStringExtra("uuid");
		id = intent.getStringExtra("id");
		name = intent.getStringExtra("name");
		Log.d("uuid", uuid + "");
		Log.d("id", id + "");
		Log.d("name", name + "");
		setContent();
		initView();
		initData();
		setOnClickListener();
		App.netManager.getAlarmMusic(handler);
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onPageStart(this.getPackageName());
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd(this.getPackageName());
		MobclickAgent.onPause(this);
	}

	public void startActivityAnim(Intent intent) {
		startActivity(intent);
		overridePendingTransition(R.anim.base_slide_right_in,
				R.anim.base_slide_remain);
	}

	void setOnClickListener() {
		Button imgBack = (Button) findViewById(R.id.backToHomePage);
		imgBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if ("ONLINE".equals(NetManager.subOnLineMap.get(uuid))) {
					saveStatus();
				} else {
					finish();
				}
			}
		});
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (null != player) {
			if (player.isPlaying()) {
				player.stop();
			}
			player.reset();
			player.release();
			player = null;
		}

		if (null != progressDialog && progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
	}

	/**
	 * setContentView 及初始化
	 */
	void setContent() {
		setContentView(R.layout.alarm_voice);
		AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		int voiceMax = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		am.setStreamVolume(AudioManager.STREAM_MUSIC, voiceMax, 0);
	};

	void initView() {
		TextView titleName = (TextView) findViewById(R.id.topLineTitle);
		titleName.setText(getString(R.string.sub_alarm_name));
		headerView = getLayoutInflater().inflate(
				R.layout.alarm_voice_list_item, null);
		headerView.findViewById(R.id.groupsDivides).setVisibility(View.VISIBLE);
		TextView tv = (TextView) headerView.findViewById(R.id.voice_item_name);
		tv.setText(getString(R.string.sub_states_null));
		cb = (CheckBox) headerView.findViewById(R.id.voice_item_check);
		headerView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				isSetted = true;
				stopPlay();
				if (-1 != groupPosition) {
					List<Map<String, Object>> child = childs.get(groupPosition);
					if (-1 != childPosition) {
						HashMap<String, Object> map = (HashMap<String, Object>) child
								.get(childPosition);
						map.put(Constants.SUB_CHECK, false);
						child.remove(childPosition);
						child.add(childPosition, map);
					}
				}
				adapter.notifyDataSetChanged();
				groupPosition = -1;
				childPosition = -1;
				cb.setChecked(!cb.isChecked());
			}
		});
		listview = (ExpandableListView) findViewById(android.R.id.list);
		listview.addHeaderView(headerView);
		initData();
		/**
		 * 使用SimpleExpandableListAdapter显示ExpandableListView 参数1.上下文对象Context
		 * 参数2.一级条目目录集合 参数3.一级条目对应的布局文件 参数4.fromto，就是map中的key，指定要显示的对象
		 * 参数5.与参数4对应，指定要显示在groups中的id 参数6.二级条目目录集合 参数7.二级条目对应的布局文件
		 * 参数8.fromto，就是map中的key，指定要显示的对象 参数9.与参数8对应，指定要显示在childs中的id
		 */

		adapter = new VoiceAdapter(this, groups, R.layout.groups_layout,
				new String[] { "group" }, new int[] { R.id.look_more }, childs,
				R.layout.alarm_voice_list_item, new String[] {
						Constants.SUB_NAME, Constants.SUB_CHECK }, new int[] {
						R.id.voice_item_name, R.id.voice_item_check });
		setListAdapter(adapter);
		for (int i = 0; i < adapter.getGroupCount(); i++) {
			listview.expandGroup(i);
		}
	};

	/**
	 * 初始化威慑语音集合
	 */
	private void initAlarmList(List<Map<String, Object>> list) {
		addMapToList(getString(R.string.sub_alarm_voice1), list.size(), list, 0);
		addMapToList(getString(R.string.sub_alarm_voice3), list.size(), list, 0);
	}

	/**
	 * 初始化小孩看护集合
	 */
	private void initChildList(List<Map<String, Object>> list) {
		addMapToList(getString(R.string.sub_child_voice1), list.size(), list, 1);
		addMapToList(getString(R.string.sub_child_voice4), list.size(), list, 1);
	}

	/**
	 * 将每个map初始化之后添加到list
	 * 
	 * @param name
	 *            内容
	 * @param position
	 *            位置
	 */
	private void addMapToList(String name, int position,
			List<Map<String, Object>> list, int groupPosition) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put(Constants.SUB_NAME, name);
		if (null != currentPlay && currentPlay.equals(name)) {
			map.put(Constants.SUB_CHECK, true);
			childPosition = position;
			this.groupPosition = groupPosition;
		} else {
			map.put(Constants.SUB_CHECK, false);
		}
		list.add(map);
	}

	/**
	 * 初始化数据
	 */
	void initData() {
		currentPlay = SharedPrefsUtil
				.getStringValue(this, Constants.AlARM_PLAY_VOICE,
						getString(R.string.sub_states_null));
		if (currentPlay.equals(getString(R.string.sub_states_null))) {
			cb.setChecked(true);
		}
		voiceMap.putAll(new SubUtils().getVoiceMap(con));
		// 创建一级条目
		groups = new ArrayList<Map<String, String>>();
		// 创建两个一级条目标题
		Map<String, String> groupTheft = new HashMap<String, String>();
		groupTheft.put("group", getString(R.string.sub_voice1));
		Map<String, String> groupChild = new HashMap<String, String>();
		groupChild.put("group", getString(R.string.sub_voice2));
		groups.add(groupTheft);
		groups.add(groupChild);

		// 创建一级条目下的的二级条目
		List<Map<String, Object>> childTheft = new ArrayList<Map<String, Object>>();
		// 同样是在一级条目目录下创建两个对应的二级条目目录
		initAlarmList(childTheft);
		// 同上
		List<Map<String, Object>> childChilds = new ArrayList<Map<String, Object>>();
		initChildList(childChilds);
		// 将二级条目放在一个集合里，供显示时使用
		childs = new ArrayList<List<Map<String, Object>>>();
		childs.add(childTheft);
		childs.add(childChilds);

	};

	/**
	 * 设置哪个二级目录被默认选中
	 */
	@Override
	public boolean setSelectedChild(int groupPosition, int childPosition,
			boolean shouldExpandGroup) {
		// do something
		return super.setSelectedChild(groupPosition, childPosition,
				shouldExpandGroup);
	}

	/**
	 * 设置哪个一级目录被默认选中
	 */
	@Override
	public void setSelectedGroup(int groupPosition) {
		// do something
		super.setSelectedGroup(groupPosition);
	}

	/**
	 * 当二级条目被点击时响应
	 */
	@Override
	public boolean onChildClick(ExpandableListView parent, View v,
			int groupPosition, int childPosition, long id) {
		isSetted = true;
		cb.setChecked(false);
		CheckBox checkBox = (CheckBox) v.findViewById(R.id.voice_item_check);
		checkBox.setChecked(!checkBox.isChecked());
		boolean checked = checkBox.isChecked();
		if (-1 != this.groupPosition) {
			List<Map<String, Object>> child = childs.get(this.groupPosition);
			if (-1 != this.childPosition) {
				HashMap<String, Object> map = (HashMap<String, Object>) child
						.get(this.childPosition);
				map.put(Constants.SUB_CHECK, false);
				child.remove(this.childPosition);
				child.add(this.childPosition, map);
			}
		}
		List<Map<String, Object>> child = childs.get(groupPosition);
		HashMap<String, Object> map = (HashMap<String, Object>) child
				.get(childPosition);
		map.put(Constants.SUB_CHECK, checked);
		child.remove(childPosition);
		child.add(childPosition, map);
		if (checked) {
			this.childPosition = childPosition;
			this.groupPosition = groupPosition;
		} else {
			this.childPosition = -1;
			this.groupPosition = -1;
		}
		String name = (String) map.get(Constants.SUB_NAME);
		adapter.notifyDataSetChanged();
		if (null != previousPlay && previousPlay != checkBox) {
			previousPlay.setChecked(false);
		}
		if (checkBox.isChecked()) {
			Object obj = voiceMap.get(name);
			if (null != player) {
				stopPlay();
			}
			if (null != obj) {
				try {
					if (obj instanceof Integer) {
						AssetFileDescriptor afd = con.getResources()
								.openRawResourceFd((Integer) obj);
						player.setDataSource(afd.getFileDescriptor(),
								afd.getStartOffset(), afd.getLength());
						afd.close();
					} else if (obj instanceof String) {
						player.setDataSource((String) obj);
					}
					player.setOnPreparedListener(new OnPreparedListener() {

						@Override
						public void onPrepared(MediaPlayer mp) {
							player.start();
						}
					});
					player.prepareAsync();
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		} else {
			stopPlay();
		}
		previousPlay = checkBox;
		return super.onChildClick(parent, v, groupPosition, childPosition, id);
	}

	private void saveStatus() {
		if (!isSetted) {
			finish();
			return;
		}
		Log.d("subonline", NetManager.subOnLineMap.get(uuid).toString());
		if (App.isLogin) {
			if (!NetManager.subOnLineMap.get(uuid).toString().equals("ONLINE")) {
				Show.toast(con, R.string.sub_off_line);
				return;
			}
		} else {
			Show.toast(con, R.string.please_login);
			return;
		}
		if (null == progressDialog) {
			progressDialog = SubUtils.showProgress(con);
		} else {
			progressDialog.show();
		}
		Device device = new Device();
		device.setDiviceId(id);
		device.setUuid(uuid);
		String dayStart = SharedPrefsUtil.getStringValue(con,
				Constants.DAY_MODE_START_TIME,
				getString(R.string.sub_mode_start_time));
		String dayStop = SharedPrefsUtil.getStringValue(con,
				Constants.DAY_MODE_STOP_TIME,
				getString(R.string.sub_mode_stop_time));
		String mesures = SharedPrefsUtil.getStringValue(con,
				Constants.ALARM_MEASURES, getString(R.string.sub_body_recg));
		String alarm = SharedPrefsUtil.getStringValue(con,
				Constants.AlARM_METHODS, getString((R.string.sub_take_one)));
		String voice = (groupPosition == -1 || childPosition == -1) ? getString(R.string.sub_states_null)
				: childs.get(groupPosition).get(childPosition)
						.get(Constants.SUB_NAME).toString();
		String nightStart = SharedPrefsUtil.getStringValue(con,
				Constants.NIGHT_MODE_START_TIME,
				getString(R.string.sub_mode_stop_time));
		String nightStop = SharedPrefsUtil.getStringValue(con,
				Constants.NIGHT_MODE_STOP_TIME,
				getString(R.string.sub_mode_start_time));
		boolean flashLight = SharedPrefsUtil.getBooleanValue(con,
				Constants.FLASH_LIGHT, true);
		TreeSet<Integer> chooseSet = subUtils.getWeekDaySet(
				con,
				SharedPrefsUtil.getSetValue(con, Constants.WEEK_DAY,
						subUtils.initWeekSet(con)));

		device.setStartTWhite(dayStart);
		device.setEndTWhite(dayStop);
		device.setDeterrenceVWhite(voice);
		device.setLarmWhite(alarm);
		device.setStartTNight(nightStart);
		device.setEndTNight(nightStop);
		device.setLarmNight(alarm);
		device.setDeterrenceVNight(voice);
		device.setHumanR(mesures.equals(getString(R.string.sub_body_recg)));
		device.setMotionD(!mesures.equals(getString(R.string.sub_body_recg)));
		device.setFlashlight(flashLight);
		device.setWeekWhite(getWeekStr(chooseSet));
		device.setWeekNight(getWeekStr(chooseSet));
		App.netManager.setCollectionTerminal(device, handler);
	}

	/**
	 * 将TreeSet 变为字符串1,2,3,...等上传
	 * */
	private String getWeekStr(TreeSet<Integer> chooseSet) {
		StringBuffer sb = new StringBuffer("");
		Iterator<Integer> it = chooseSet.iterator();
		while (it.hasNext()) {
			int day = it.next();
			sb.append(day);
			sb.append(",");
		}
		String week = sb.toString();
		return week.substring(0, week.length() - 1);
	}

	public void stopPlay() {
		if (null != player) {
			if (player.isPlaying()) {
				player.stop();
			}
			player.reset();
		}
	}

	class VoiceAdapter extends SimpleExpandableListAdapter {

		public VoiceAdapter(Context context,
				List<? extends Map<String, ?>> groupData, int groupLayout,
				String[] groupFrom, int[] groupTo,
				List<? extends List<? extends Map<String, ?>>> childData,
				int childLayout, String[] childFrom, int[] childTo) {
			super(context, groupData, groupLayout, groupFrom, groupTo,
					childData, childLayout, childFrom, childTo);
			// TODO Auto-generated constructor stub
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			View v = super.getGroupView(groupPosition, isExpanded, convertView,
					parent);
			if (0 == groupPosition) {
				v.findViewById(R.id.groupsDivides).setVisibility(View.GONE);
			} else {
				v.findViewById(R.id.groupsDivides).setVisibility(View.VISIBLE);
			}
			return v;

		}

		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View v;
			if (convertView == null) {
				v = newChildView(isLastChild, parent);
			} else {
				v = convertView;
			}
			CheckBox checkBox = (CheckBox) v
					.findViewById(R.id.voice_item_check);
			HashMap<String, Object> map = (HashMap<String, Object>) childs.get(
					groupPosition).get(childPosition);
			checkBox.setChecked((Boolean) map.get(Constants.SUB_CHECK));
			TextView name = (TextView) v.findViewById(R.id.voice_item_name);
			name.setText(map.get(Constants.SUB_NAME).toString());
			return v;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			if ("ONLINE".equals(NetManager.subOnLineMap.get(uuid))) {
				saveStatus();
			} else {
				finish();
			}
			break;
		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}
}
